const { Category } = require('../models')
const { Existing, AuthFailed, NotFound } = require('../core/http-exception')
const { redis } = require('../common')
const { Op } = require('sequelize')

class CategoryController {
  static async create(data) {
    const flag = await Category.findOne({
      where: {
        name: data.get('name'),
      }
    })

    if(flag){
      throw new Existing('这个名称已经存在');
    }

    const category = await Category.create({
      name: data.get('name'),
      type: data.get('type')
    })

    if(category.type == 'label'){
      const key = `category_name_${category.name}_type_${category.type}`
      await redis.set('content', key, 60 * 60 * 24 * 3)
    }

    return category.id;
  }

  static async getList(v){
    const { keyword, type, page = 1, size = 10, order = 'DESC' } = v.get();
    const key = `category_list_keyword_${keyword}_type_${type}_page_${page}_size_${size}_order_${order}`;   
    const cache = await redis.get('content', key);
    if(cache){
      const result = JSON.parse(cache);
      result.cache = true;
      return result;
    }

    let filter = {
    }
    if(type){
      filter.type = type;
    }
    if(keyword){
      filter.name = {
        [Op.like]: `%${keyword}%`
      }
    }

    const categorys = await Category.findAndCountAll({
      attributes: ['id', 'name', 'type'],
      where: filter,
      limit: parseInt(size),
      offset: (page - 1) * parseInt(size),
      order: [['created_at', order]]
    })

    const result = {
      list: categorys.rows,
      meta: {
        total: categorys.count,
        page_size: size,
        current_page: parseInt(page),
        total_pages: Math.ceil(categorys.count / size)
      }
    }

    await redis.set('content', key, JSON.stringify(result), 60);

    return result;
  }

  static async delete(data){
    const category = await Category.findOne({
      where: {
        id: data.get('id')
      }
    })

    if(!category){
      throw new NotFound('不存在这个标签')
    }

    if (category.type == 'label') {
      const key = `category_name_${category.name}_type_${category.type}`
      await redis.del('content', key, 60 * 60 * 24 * 3)
    }

    await category.destroy();
  }

  static async find(data){
    const category = await Category.findAll({
      where: {
        name: {
          [Op.like]: `%${data.get('query')}%`
        }
      },
      attributes: [
        'id', 'name'
      ]
    })

    return category;
  }
}

module.exports = CategoryController
